{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    " ![](http://onm3nv9z1.bkt.clouddn.com/%E5%AE%BD%E5%9B%BE-1205x420.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 求和\n",
    "### 两数求和"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "输入第一个数字：6\n",
      "输入第二个数字：2\n",
      "数字6和2相加结果为：8.0\n"
     ]
    }
   ],
   "source": [
    "# 用户输入数字\n",
    "num1 = input('输入第一个数字：')\n",
    "num2 = input('输入第二个数字：')\n",
    "\n",
    "# 求和\n",
    "sum = float(num1) + float(num2)\n",
    "\n",
    "# 显示计算结果\n",
    "print('数字{0}和{1}相加结果为：{2}'.format(num1, num2, sum))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**提示：**  input()方法返回一个字符串，所以我们需要使用 float() 方法将字符串转换为数字。 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "输入第一个数字：5\n",
      "输入第二个数字：6\n",
      "两数之和为: 11.0\n"
     ]
    }
   ],
   "source": [
    "## 将以上运算，合并为一行代码\n",
    "print('两数之和为: %.1f' %(float(input('输入第一个数字：'))+float(input('输入第二个数字：'))))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 循环求和"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "你想从1加到几？请输入：9999\n",
      "49995000\n"
     ]
    }
   ],
   "source": [
    "sum = 0\n",
    "n = int(input(\"你想从1加到几？请输入：\"))\n",
    "# 计算1到n之间的和\n",
    "for i in range(1, n+1):\n",
    "    sum = sum + i\n",
    "print(sum)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 求平方和\n",
    "$1²+2²+3²+...+100²$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "你想从1加到几？请输入：3\n",
      "12\n"
     ]
    }
   ],
   "source": [
    "sum = 0\n",
    "n = int(input(\"你想从1加到几？请输入：\"))\n",
    "# 计算1到n之间的和\n",
    "for i in range(1, n+1):\n",
    "    x = i**2\n",
    "    sum = x + i\n",
    "print(sum)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 求平方根\n",
    "用户输入一个数字，并计算这个数字的平方根：\n",
    "\n",
    "平方根，又叫二次方根，表示为〔√￣〕，如：数学语言为：√￣16=4。语言描述为：根号下16=4。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "请输入一个数字： 3\n",
      " 3.00 的平方根为 1.73\n"
     ]
    }
   ],
   "source": [
    "num = float(input('请输入一个数字： '))\n",
    "num_sqrt = num ** 0.5\n",
    "print(' %0.2f 的平方根为 %.2f' %(num ,num_sqrt))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**思考：**以上程序只适用于正数。负数和复数应该怎样实现呢？  \n",
    "实数范围内负数没有平方根，复数范围内，负数有两个虚数平方根。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "请输入一个数字: 2\n",
      "2 的平方根为 1.41+0.00j\n"
     ]
    }
   ],
   "source": [
    "# 导入复数数学模块\n",
    "import cmath\n",
    "\n",
    "num = int(input(\"请输入一个数字: \"))\n",
    "num_sqrt = cmath.sqrt(num)\n",
    "# your code here\n",
    "print('{0} 的平方根为 {1:0.2f}+{2:0.2f}j'.format(num ,num_sqrt.real,num_sqrt.imag))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**提示：** 该实例中，我们使用了 cmath (complex math) 模块的 sqrt() 方法。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 求解二元一次方程组\n",
    "$a₁x + b₁y = c₁$    \n",
    "$a₂x + b₂y = c₂$  \n",
    "其中$a₁b₂ - a₂b₁ ≠ 0$"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 求二次方程"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "$b^2-4ac$用来判断一元二次方程的根的个数。  \n",
    "1、当$b^2-4ac＞0$时，方程具有两个不相等实数根。   \n",
    "2、当$b^2-4ac=0$时，方程具有一个实数根。（或两个相等实数根）    \n",
    "3、当$b^2-4ac＜0$时，方程没有实数根。  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "以下为通过用户输入数字，并计算二次方程；\n",
    "\n",
    "代码如下："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "输入 a: 1\n",
      "输入 b: 4\n",
      "输入 c: 2\n",
      "结果为 (-3.414213562373095+0j) 和 (-0.5857864376269049+0j)\n"
     ]
    }
   ],
   "source": [
    "# 二次方程式 ax**2 + bx + c = 0\n",
    "# a、b、c 由用户提供\n",
    "\n",
    "# 导入 cmath(复杂数学运算) 模块\n",
    "import cmath\n",
    "\n",
    "a = float(input('输入 a: '))\n",
    "b = float(input('输入 b: '))\n",
    "c = float(input('输入 c: '))\n",
    "\n",
    "# 计算\n",
    "d = (b**2) - (4*a*c)\n",
    "\n",
    "# 两种求解方式\n",
    "sol1 = (-b-cmath.sqrt(d))/(2*a)\n",
    "# your code here: sol2 = \n",
    "sol2 = (-b+cmath.sqrt(d))/(2*a)\n",
    "\n",
    "print('结果为 {0} 和 {1}'.format(sol1,sol2))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "输入 a: 1\n",
      "输入 b: 4\n",
      "输入 c: 2\n",
      "结果为 (-3.414213562373095+0j) 和 (-0.5857864376269049+0j)\n"
     ]
    }
   ],
   "source": [
    "# 增加判断条件\n",
    "import cmath\n",
    "\n",
    "a = float(input('输入 a: '))\n",
    "b = float(input('输入 b: '))\n",
    "c = float(input('输入 c: '))\n",
    "\n",
    "# 计算\n",
    "d = (b**2) - (4*a*c)\n",
    "\n",
    "if (d>0):\n",
    "    sol1 = (-b-cmath.sqrt(d))/(2*a)\n",
    "    sol2 = (-b+cmath.sqrt(d))/(2*a)\n",
    "    print('结果为 {0} 和 {1}'.format(sol1,sol2))\n",
    "elif (d==0): \n",
    "    sol1 = (-b-cmath.sqrt(d))/(2*a)\n",
    "    print('结果为{}'.format(sol1))\n",
    "else:\n",
    "    print(\"该方程没有实数根。\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**提示：该实例中，我们使用了 cmath (complex math) 模块的 sqrt() 方法 来计算平方根。**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 求三角形的面积\n",
    "以下为通过用户输入三角形三边长度，并计算三角形的面积；"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**海伦公式：**  \n",
    "假设在平面内，有一个三角形，边长分别为a、b、c，三角形的面积S可由以下公式求得：  \n",
    "$\\sqrt{p(p-a)(p-b)(p-c)}$  \n",
    "而公式里的p为半周长（周长的一半）：  \n",
    "$p=\\frac{1}{2}(a+b+c)$"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### if……else……语句"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "输入三角形第一边长：1\n",
      "输入三角形第二边长：2\n",
      "输入三角形第三边长：3\n",
      "输入的边构不成三角形，请重新输入！\n"
     ]
    }
   ],
   "source": [
    "a = float (input ('输入三角形第一边长：'))\n",
    "b = float (input ('输入三角形第二边长：'))\n",
    "c = float (input ('输入三角形第三边长：'))\n",
    "if (a+b>c and a+c>b and b+c>a):\n",
    "    p = (a+b+c)/2\n",
    "    area = (p*(p-a)*(p-b)*(p-c))**0.5\n",
    "    print ('三角形面积为：%0.2f' %area)\n",
    "else:\n",
    "    print ('输入的边构不成三角形，请重新输入！')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### while循环\n",
    "Python不支持do...while语法；  \n",
    "以使用 while（无限循环）和 break 组合起来实现 do...while 语法。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "第一边长：1\n",
      "第二边长：2\n",
      "第三边长：3\n",
      "输入的边构不成三角形，请重新输入！\n",
      "第一边长：3\n",
      "第二边长：4\n",
      "第三边长：5\n",
      "三角形面积为：6.00\n"
     ]
    }
   ],
   "source": [
    "a = float (input ('第一边长：'))\n",
    "b = float (input ('第二边长：'))\n",
    "c = float (input ('第三边长：'))\n",
    "while (a+b<=c or a+c<=b or b+c<=a):\n",
    "    print ('输入的边构不成三角形，请重新输入！')\n",
    "    a = float (input ('第一边长：'))\n",
    "    b = float (input ('第二边长：'))\n",
    "    c = float (input ('第三边长：'))\n",
    "    \n",
    "p = (a+b+c)/2\n",
    "area = (p*(p-a)*(p-b)*(p-c))**0.5\n",
    "print ('三角形面积为：%0.2f' %area)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 生成随机数\n",
    "以下演示了如何生成一个随机数；\n",
    "\n",
    "代码如下："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5\n"
     ]
    }
   ],
   "source": [
    "# 生成 0 ~ 9 之间的随机数\n",
    "\n",
    "# 导入 random(随机数) 模块\n",
    "import random\n",
    " \n",
    "print(random.randint(0,9))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**提示：以上实例我们使用了 random 模块的 randint() 函数来生成随机数，你每次执行后都返回不同的数字（0 到 9）**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 将摄氏温度转化为华氏温度\n",
    "\n",
    "摄氏温度转华氏温度的公式为 celsius * 1.8 = fahrenheit - 32。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "以下演示了如何将摄氏温度转华氏温度；\n",
    "\n",
    "代码如下："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "输入摄氏温度: 5\n",
      "5.0 摄氏温度转为华氏温度为 41.0 \n"
     ]
    }
   ],
   "source": [
    "# 用户输入摄氏温度(Celsius)\n",
    " \n",
    "# 接收用户输入\n",
    "celsius = float(input('输入摄氏温度: '))\n",
    "\n",
    "# 计算华氏温度(fahrenheit)\n",
    "fahrenheit = celsius*1.8 + 32\n",
    "print('%0.1f 摄氏温度转为华氏温度为 %0.1f ' %(celsius,fahrenheit))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 交换变量\n",
    "用户输入两个变量，并相互交换。\n",
    "\n",
    "### 使用临时变量"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "输入 x 值: 5\n",
      "输入 y 值: 1\n",
      "交换后 x 的值为: 1\n",
      "交换后 y 的值为: 5\n"
     ]
    }
   ],
   "source": [
    "# 用户输入\n",
    "\n",
    "x = input('输入 x 值: ')\n",
    "y = input('输入 y 值: ')\n",
    "\n",
    "# 创建临时变量，并交换。倒油瓶\n",
    "temp = x\n",
    "x = y\n",
    "y = temp\n",
    "\n",
    "print('交换后 x 的值为: {}'.format(x))\n",
    "print('交换后 y 的值为: {}'.format(y))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "### 不使用临时变量\n",
    "\n",
    "我们也可以不创建临时变量，用一个非常优雅的方式来交换变量。  \n",
    "x,y = y,x"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "所以上述实例可以修改为："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "输入 x 值: 5\n",
      "输入 y 值: 1\n",
      "交换后 x 的值为: 1\n",
      "交换后 y 的值为: 5\n"
     ]
    }
   ],
   "source": [
    "# -*- coding: UTF-8 -*-\n",
    "\n",
    "# Filename : test.py\n",
    "# author by : www.runoob.com\n",
    "\n",
    "# 用户输入\n",
    "\n",
    "x = input('输入 x 值: ')\n",
    "y = input('输入 y 值: ')\n",
    "\n",
    "# 不使用临时变量\n",
    "x,y = y,x\n",
    "\n",
    "print('交换后 x 的值为: {}'.format(x))\n",
    "print('交换后 y 的值为: {}'.format(y))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "## 找出10000之内的所有完数\n",
    "\n",
    "编程找出10000之内的所有完数，并输出该完数及对应的因子。\n",
    "- 一个数如果恰好等于它的因子之和，这个数就称为“完数”。\n",
    "- 例如，6的因子为1、2、3，而6=1+2+3，因此6是完数；28=1+2+3+...+6+7是完数；496=1+2+3+...+30+31是完数。\n",
    "\n",
    "代码如下："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "6 [1, 2, 3]\n",
      "28 [1, 2, 4, 7, 14]\n",
      "496 [1, 2, 4, 8, 16, 31, 62, 124, 248]\n"
     ]
    }
   ],
   "source": [
    "def wanshu(N):\n",
    "    factors = [] # 定义一个空列表\n",
    "    for i in range(1, N):\n",
    "        if (N % i) == 0:\n",
    "            factors.append(i)   # find all factors\n",
    "    if sum(factors) == N:\n",
    "        return True, factors\n",
    "    else:\n",
    "        return False, []\n",
    "\n",
    "for i in range(1, 1000):    # 请加注释\n",
    "    isW, facs = wanshu(i)    # 请加注释\n",
    "    if isW:                  # 请加注释\n",
    "        print (i, facs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "21"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 对列表元素求和\n",
    "list1 = [1,2,3,4,5,6]\n",
    "a = sum(list1)\n",
    "a"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 摘录网页HTML源码\n",
    "摘录网页HTML源码，粘贴到input.txt，统计其中英文字母、空格、数字和其他字符的个数并输出。\n",
    "\n",
    "代码如下："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "letter: 2747\n",
      "blank: 137\n",
      "number: 236\n",
      "other: 998\n"
     ]
    }
   ],
   "source": [
    "counts = {\"letter\": 0, \"blank\": 0, \"number\": 0, \"other\": 0}\n",
    "\n",
    "f = open('./input_1.txt', 'r')        #代码完整且正确，请使用自己准备的文档完成作业\n",
    "contents = f.readlines()\n",
    "f.close()\n",
    "for coni in contents:\n",
    "    tmp = coni.strip()\n",
    "    for ci in tmp:\n",
    "        if ci.isalpha():    # is letter?\n",
    "            counts[\"letter\"] += 1\n",
    "        elif ci.isspace():  # is space?\n",
    "            counts[\"blank\"] += 1\n",
    "        elif ci.isdigit():  # is number?\n",
    "            counts[\"number\"] += 1\n",
    "        else:               # other\n",
    "            counts[\"other\"] += 1\n",
    "for item in counts.items():\n",
    "    print (item[0] + \": \" + str(item[1]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 在网上摘录一段英文文本\n",
    "在网上摘录一段英文文本(尽量长一些)，粘贴到input.txt，统计其中每个单词的词频(出现的次数)，并按照词频的顺序写入out.txt文件，每一行的内容为“单词:频次”\n",
    "\n",
    "代码如下："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "ename": "UnicodeDecodeError",
     "evalue": "'gbk' codec can't decode byte 0x9d in position 1080: illegal multibyte sequence",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mUnicodeDecodeError\u001b[0m                        Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-11-018d3b236e2e>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[0;32m      2\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      3\u001b[0m \u001b[0mf\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mopen\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'./input_2.txt'\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;34m'r'\u001b[0m\u001b[1;33m)\u001b[0m      \u001b[1;31m#代码完整且正确，请使用自己准备的文档完成作业\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 4\u001b[1;33m \u001b[0mcontents\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mf\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mread\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m      5\u001b[0m \u001b[0mf\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mclose\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      6\u001b[0m \u001b[0mwords\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mre\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mfindall\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34mr'\\w+'\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mcontents\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;31mUnicodeDecodeError\u001b[0m: 'gbk' codec can't decode byte 0x9d in position 1080: illegal multibyte sequence"
     ]
    }
   ],
   "source": [
    "import re\n",
    "\n",
    "f = open('./input_2.txt', 'r')      #代码完整且正确，请使用自己准备的文档完成作业\n",
    "contents = f.read()\n",
    "f.close()\n",
    "words = re.findall(r'\\w+', contents)\n",
    "counts = {}\n",
    "for wordi in words:\n",
    "    if wordi in counts:\n",
    "        counts[wordi] += 1\n",
    "    else:\n",
    "        counts[wordi] = 1\n",
    "tmp = sorted(counts.items(), key = lambda item:item[1], reverse = True)\n",
    "\n",
    "fw = open('./out.txt', 'w')\n",
    "for ti in tmp:\n",
    "    fw.write(ti[0] + \": \" + str(ti[1]) + \"\\n\")\n",
    "fw.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 调出字符串\n",
    "调出字符串'AV is largest Analytics community of India'中每个字母Extract each character\n",
    "\n",
    "代码如下："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['A', 'V', 'i', 's', 'l', 'a', 'r', 'g', 'e', 's', 't', 'A', 'n', 'a', 'l', 'y', 't', 'i', 'c', 's', 'c', 'o', 'm', 'm', 'u', 'n', 'i', 't', 'y', 'o', 'f', 'I', 'n', 'd', 'i', 'a']\n"
     ]
    }
   ],
   "source": [
    "import re\n",
    "\n",
    "result = re.findall(r'\\w','AV is largest Analytics community of India')\n",
    "print(result)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**提示：用“\\w“**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 获取昨天的日期"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2019-06-27\n"
     ]
    }
   ],
   "source": [
    "# 引入 datetime 模块\n",
    "import datetime\n",
    "\n",
    "def getYesterday(): \n",
    "    today=datetime.date.today()   # 请加注释\n",
    "    oneday=datetime.timedelta(days=1)   # 请加注释\n",
    "    yesterday=today-oneday    # 请加注释\n",
    "    return yesterday\n",
    "\n",
    "# 输出\n",
    "print(getYesterday())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [],
   "source": [
    "# help(datetime.timedelta)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "datetime.date(2019, 6, 28)"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 获取今天的日期\n",
    "today = datetime.date.today()\n",
    "today"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "datetime.timedelta(1)"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 定义需要增减的时间量\n",
    "oneday = datetime.timedelta(days=1)\n",
    "oneday"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "datetime.date(2019, 6, 27)"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 获取昨天的日期\n",
    "yesterday = today-oneday\n",
    "yesterday"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "datetime.date(2019, 6, 29)"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 获取明天的日期\n",
    "tomorrow = today+oneday\n",
    "tomorrow"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 生成日历"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "输入年份: 2019\n",
      "输入月份: 6\n",
      "     June 2019\n",
      "Mo Tu We Th Fr Sa Su\n",
      "                1  2\n",
      " 3  4  5  6  7  8  9\n",
      "10 11 12 13 14 15 16\n",
      "17 18 19 20 21 22 23\n",
      "24 25 26 27 28 29 30\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# 引入日历模块\n",
    "import calendar\n",
    "\n",
    "# 输入指定年月\n",
    "yy = int(input(\"输入年份: \"))\n",
    "mm = int(input(\"输入月份: \"))\n",
    "\n",
    "# 显示日历\n",
    "print(calendar.month(yy,mm))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 最大公约数算法\n",
    "greatest common divisor"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "输入第一个数字: 16\n",
      "输入第二个数字: 12\n",
      "16 和 12 的最大公约数为 4\n"
     ]
    }
   ],
   "source": [
    "# 定义一个函数，该函数返回两个数的最大公约数\n",
    "def gcd(x, y):\n",
    "   # 获取两数中的较小值\n",
    "   if x > y:\n",
    "       smaller = y\n",
    "   else:\n",
    "       smaller = x\n",
    " \n",
    "   for i in range(1,smaller + 1):\n",
    "       if((x % i == 0) and (y % i == 0)):\n",
    "           gcd = i\n",
    " \n",
    "   return gcd\n",
    "\n",
    "# 用户输入两个数字\n",
    "num1 = int(input(\"输入第一个数字: \"))\n",
    "num2 = int(input(\"输入第二个数字: \"))\n",
    " \n",
    "print( num1,\"和\", num2,\"的最大公约数为\", gcd(num1, num2))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 最小公倍数算法\n",
    "Least Common Multiple"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "输入第一个数字: 16\n",
      "输入第二个数字: 12\n",
      "16 和 12 的最小公倍数为 48\n"
     ]
    }
   ],
   "source": [
    "# 定义函数\n",
    "def lcm(x, y):\n",
    " \n",
    "   #  获取两数中的较大值\n",
    "   if x > y:\n",
    "       greater = x\n",
    "   else:\n",
    "       greater = y\n",
    " \n",
    "   while(True):\n",
    "       if((greater % x == 0) and (greater % y == 0)):\n",
    "           lcm = greater\n",
    "           break;\n",
    "       greater += 1\n",
    " \n",
    "   return lcm\n",
    "\n",
    "# 获取用户输入\n",
    "num1 = int(input(\"输入第一个数字: \"))\n",
    "num2 = int(input(\"输入第二个数字: \"))\n",
    " \n",
    "print( num1,\"和\", num2,\"的最小公倍数为\", lcm(num1, num2))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 因数分解\n",
    "使用递归法对整数进行因数分解。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "ename": "SyntaxError",
     "evalue": "unexpected EOF while parsing (<string>, line 0)",
     "output_type": "error",
     "traceback": [
      "Traceback \u001b[1;36m(most recent call last)\u001b[0m:\n",
      "  File \u001b[0;32m\"D:\\pcApp\\Anaconda3\\lib\\site-packages\\IPython\\core\\interactiveshell.py\"\u001b[0m, line \u001b[0;32m2963\u001b[0m, in \u001b[0;35mrun_code\u001b[0m\n    exec(code_obj, self.user_global_ns, self.user_ns)\n",
      "\u001b[1;36m  File \u001b[1;32m\"<ipython-input-9-ef678d4d65ed>\"\u001b[1;36m, line \u001b[1;32m20\u001b[1;36m, in \u001b[1;35m<module>\u001b[1;36m\u001b[0m\n\u001b[1;33m    if n == eval(result):\u001b[0m\n",
      "\u001b[1;36m  File \u001b[1;32m\"<string>\"\u001b[1;36m, line \u001b[1;32munknown\u001b[0m\n\u001b[1;33m    \u001b[0m\n\u001b[1;37m    ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m unexpected EOF while parsing\n"
     ]
    }
   ],
   "source": [
    "from random import randint\n",
    "\n",
    "def factors(num, fac=[]):\n",
    "    # 每次都从2开始查找因数\n",
    "    for i in range(2, int(num**0.5)+1):\n",
    "        if num % i == 0:\n",
    "            fac.append(i)\n",
    "            # 继续分解，重复这个过程\n",
    "            factors(num//i, fac)\n",
    "            # 注意，这个break很重要\n",
    "            break\n",
    "    else:\n",
    "        # 不可分解了，自身也是个因数\n",
    "        fac.append(num)\n",
    "    \n",
    "facs = []\n",
    "n = randint(2, 10**8)\n",
    "factors = (n, facs) \n",
    "result = '*'.join(map(str, facs))\n",
    "if n == eval(result):\n",
    "    print(n, '= ' + result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 查找最大数\n",
    "任意定义n个数(有整型和浮点型)，通过比较判断，输出其最大者。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The maximum value is 45\n"
     ]
    }
   ],
   "source": [
    "nums = [3, 12.5, 5.562, 45, 11, -1]  # 以list的形式定义n个数\n",
    "\n",
    "# 先假设第一个数为最大数\n",
    "maxNum = nums[0] \n",
    "\n",
    "for i in range(1, len(nums)):\n",
    "    if (nums[i]>nums[i-1]):\n",
    "        maxNum = nums[i]\n",
    "        \n",
    "print (\"The maximum value is\", maxNum)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 生成特定数\n",
    "列表推导式（list comprehension）是一种简化代码的优美方法。  \n",
    "用list comprehension生成1-1000之间所有能被3整除不能被5整除的数。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[3, 6, 9, 12, 18, 21, 24, 27, 33, 36, 39, 42, 48, 51, 54, 57, 63, 66, 69, 72, 78, 81, 84, 87, 93, 96, 99, 102, 108, 111, 114, 117, 123, 126, 129, 132, 138, 141, 144, 147, 153, 156, 159, 162, 168, 171, 174, 177, 183, 186, 189, 192, 198, 201, 204, 207, 213, 216, 219, 222, 228, 231, 234, 237, 243, 246, 249, 252, 258, 261, 264, 267, 273, 276, 279, 282, 288, 291, 294, 297, 303, 306, 309, 312, 318, 321, 324, 327, 333, 336, 339, 342, 348, 351, 354, 357, 363, 366, 369, 372, 378, 381, 384, 387, 393, 396, 399, 402, 408, 411, 414, 417, 423, 426, 429, 432, 438, 441, 444, 447, 453, 456, 459, 462, 468, 471, 474, 477, 483, 486, 489, 492, 498, 501, 504, 507, 513, 516, 519, 522, 528, 531, 534, 537, 543, 546, 549, 552, 558, 561, 564, 567, 573, 576, 579, 582, 588, 591, 594, 597, 603, 606, 609, 612, 618, 621, 624, 627, 633, 636, 639, 642, 648, 651, 654, 657, 663, 666, 669, 672, 678, 681, 684, 687, 693, 696, 699, 702, 708, 711, 714, 717, 723, 726, 729, 732, 738, 741, 744, 747, 753, 756, 759, 762, 768, 771, 774, 777, 783, 786, 789, 792, 798, 801, 804, 807, 813, 816, 819, 822, 828, 831, 834, 837, 843, 846, 849, 852, 858, 861, 864, 867, 873, 876, 879, 882, 888, 891, 894, 897, 903, 906, 909, 912, 918, 921, 924, 927, 933, 936, 939, 942, 948, 951, 954, 957, 963, 966, 969, 972, 978, 981, 984, 987, 993, 996, 999]\n"
     ]
    }
   ],
   "source": [
    "nums = [num for num in range(1, 1001) if num % 3 == 0 and num % 5 != 0]\n",
    "print (nums)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 列表切片\n",
    "取出上述列表中前10个数，最后5个数，下标为偶数的数，并把列表逆序。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[3, 6, 9, 12, 18, 21, 24, 27, 33, 36, 39, 42, 48, 51, 54, 57, 63, 66, 69, 72, 78, 81, 84, 87, 93, 96, 99, 102, 108, 111, 114, 117, 123, 126, 129, 132, 138, 141, 144, 147, 153, 156, 159, 162, 168, 171, 174, 177, 183, 186, 189, 192, 198, 201, 204, 207, 213, 216, 219, 222, 228, 231, 234, 237, 243, 246, 249, 252, 258, 261, 264, 267, 273, 276, 279, 282, 288, 291, 294, 297, 303, 306, 309, 312, 318, 321, 324, 327, 333, 336, 339, 342, 348, 351, 354, 357, 363, 366, 369, 372, 378, 381, 384, 387, 393, 396, 399, 402, 408, 411, 414, 417, 423, 426, 429, 432, 438, 441, 444, 447, 453, 456, 459, 462, 468, 471, 474, 477, 483, 486, 489, 492, 498, 501, 504, 507, 513, 516, 519, 522, 528, 531, 534, 537, 543, 546, 549, 552, 558, 561, 564, 567, 573, 576, 579, 582, 588, 591, 594, 597, 603, 606, 609, 612, 618, 621, 624, 627, 633, 636, 639, 642, 648, 651, 654, 657, 663, 666, 669, 672, 678, 681, 684, 687, 693, 696, 699, 702, 708, 711, 714, 717, 723, 726, 729, 732, 738, 741, 744, 747, 753, 756, 759, 762, 768, 771, 774, 777, 783, 786, 789, 792, 798, 801, 804, 807, 813, 816, 819, 822, 828, 831, 834, 837, 843, 846, 849, 852, 858, 861, 864, 867, 873, 876, 879, 882, 888, 891, 894, 897, 903, 906, 909, 912, 918, 921, 924, 927, 933, 936, 939, 942, 948, 951, 954, 957, 963, 966, 969, 972, 978, 981, 984, 987, 993, 996, 999]\n"
     ]
    }
   ],
   "source": [
    "nums = [num for num in range(1, 1001) if num % 3 == 0 and num % 5 != 0]\n",
    "print(nums)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[3, 6, 9, 12, 18, 21, 24, 27, 33, 36]\n"
     ]
    }
   ],
   "source": [
    "# 取前10个数\n",
    "print (nums[:10]) "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[984, 987, 993, 996, 999]\n"
     ]
    }
   ],
   "source": [
    "# 取后5个数\n",
    "print (nums[-5:]) "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[3, 9, 18, 24, 33, 39, 48, 54, 63, 69, 78, 84, 93, 99, 108, 114, 123, 129, 138, 144, 153, 159, 168, 174, 183, 189, 198, 204, 213, 219, 228, 234, 243, 249, 258, 264, 273, 279, 288, 294, 303, 309, 318, 324, 333, 339, 348, 354, 363, 369, 378, 384, 393, 399, 408, 414, 423, 429, 438, 444, 453, 459, 468, 474, 483, 489, 498, 504, 513, 519, 528, 534, 543, 549, 558, 564, 573, 579, 588, 594, 603, 609, 618, 624, 633, 639, 648, 654, 663, 669, 678, 684, 693, 699, 708, 714, 723, 729, 738, 744, 753, 759, 768, 774, 783, 789, 798, 804, 813, 819, 828, 834, 843, 849, 858, 864, 873, 879, 888, 894, 903, 909, 918, 924, 933, 939, 948, 954, 963, 969, 978, 984, 993, 999]\n"
     ]
    }
   ],
   "source": [
    "# 下标为偶数的数\n",
    "print (nums[::2]) "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[6, 12, 18, 24, 36, 42, 48, 54, 66, 72, 78, 84, 96, 102, 108, 114, 126, 132, 138, 144, 156, 162, 168, 174, 186, 192, 198, 204, 216, 222, 228, 234, 246, 252, 258, 264, 276, 282, 288, 294, 306, 312, 318, 324, 336, 342, 348, 354, 366, 372, 378, 384, 396, 402, 408, 414, 426, 432, 438, 444, 456, 462, 468, 474, 486, 492, 498, 504, 516, 522, 528, 534, 546, 552, 558, 564, 576, 582, 588, 594, 606, 612, 618, 624, 636, 642, 648, 654, 666, 672, 678, 684, 696, 702, 708, 714, 726, 732, 738, 744, 756, 762, 768, 774, 786, 792, 798, 804, 816, 822, 828, 834, 846, 852, 858, 864, 876, 882, 888, 894, 906, 912, 918, 924, 936, 942, 948, 954, 966, 972, 978, 984, 996]\n"
     ]
    }
   ],
   "source": [
    "# 使用列表推导式，取出其中所有的偶数\n",
    "even_nums = [even_nums for even_nums in nums if even_nums % 2 == 0]\n",
    "print(even_nums)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[999, 996, 993, 987, 984, 981, 978, 972, 969, 966, 963, 957, 954, 951, 948, 942, 939, 936, 933, 927, 924, 921, 918, 912, 909, 906, 903, 897, 894, 891, 888, 882, 879, 876, 873, 867, 864, 861, 858, 852, 849, 846, 843, 837, 834, 831, 828, 822, 819, 816, 813, 807, 804, 801, 798, 792, 789, 786, 783, 777, 774, 771, 768, 762, 759, 756, 753, 747, 744, 741, 738, 732, 729, 726, 723, 717, 714, 711, 708, 702, 699, 696, 693, 687, 684, 681, 678, 672, 669, 666, 663, 657, 654, 651, 648, 642, 639, 636, 633, 627, 624, 621, 618, 612, 609, 606, 603, 597, 594, 591, 588, 582, 579, 576, 573, 567, 564, 561, 558, 552, 549, 546, 543, 537, 534, 531, 528, 522, 519, 516, 513, 507, 504, 501, 498, 492, 489, 486, 483, 477, 474, 471, 468, 462, 459, 456, 453, 447, 444, 441, 438, 432, 429, 426, 423, 417, 414, 411, 408, 402, 399, 396, 393, 387, 384, 381, 378, 372, 369, 366, 363, 357, 354, 351, 348, 342, 339, 336, 333, 327, 324, 321, 318, 312, 309, 306, 303, 297, 294, 291, 288, 282, 279, 276, 273, 267, 264, 261, 258, 252, 249, 246, 243, 237, 234, 231, 228, 222, 219, 216, 213, 207, 204, 201, 198, 192, 189, 186, 183, 177, 174, 171, 168, 162, 159, 156, 153, 147, 144, 141, 138, 132, 129, 126, 123, 117, 114, 111, 108, 102, 99, 96, 93, 87, 84, 81, 78, 72, 69, 66, 63, 57, 54, 51, 48, 42, 39, 36, 33, 27, 24, 21, 18, 12, 9, 6, 3]\n"
     ]
    }
   ],
   "source": [
    "# 把列表逆序\n",
    "print (sorted(nums, reverse = True)) "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "## 连本带息翻番\n",
    "定义函数：对于给定的银行定期利率(输入)，计算多少年后可以连本带息翻番。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "请输入利率：0.023\n",
      "31 years\n"
     ]
    }
   ],
   "source": [
    "def helper(rates):\n",
    "    n = 1\n",
    "    while True:\n",
    "        if (1 + rates) ** n >= 2:\n",
    "            break\n",
    "        n += 1\n",
    "    print (n, \"years\")\n",
    "\n",
    "rate = float(input(\"请输入利率：\"))\n",
    "helper(rate)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "## 九九乘法表"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1x1=1\t\n",
      "2x1=2\t2x2=4\t\n",
      "3x1=3\t3x2=6\t3x3=9\t\n",
      "4x1=4\t4x2=8\t4x3=12\t4x4=16\t\n",
      "5x1=5\t5x2=10\t5x3=15\t5x4=20\t5x5=25\t\n",
      "6x1=6\t6x2=12\t6x3=18\t6x4=24\t6x5=30\t6x6=36\t\n",
      "7x1=7\t7x2=14\t7x3=21\t7x4=28\t7x5=35\t7x6=42\t7x7=49\t\n",
      "8x1=8\t8x2=16\t8x3=24\t8x4=32\t8x5=40\t8x6=48\t8x7=56\t8x8=64\t\n",
      "9x1=9\t9x2=18\t9x3=27\t9x4=36\t9x5=45\t9x6=54\t9x7=63\t9x8=72\t9x9=81\t\n"
     ]
    }
   ],
   "source": [
    "# 九九乘法表\n",
    "for i in range(1, 10):\n",
    "        for j in range(1, i+1):\n",
    "            print('{}x{}={}\\t'.format(i, j, i*j), end='')\n",
    "        print()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": true
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
